package com.jydd.singlekotlinmvvm.comm.repo

import android.content.Context
import androidx.core.content.edit
import androidx.room.Room
import com.jydd.singlekotlinmvvm.comm.Constant
import com.jydd.singlekotlinmvvm.comm.GithubConfig
import com.jydd.singlekotlinmvvm.comm.base.BaseDataSource
import com.jydd.singlekotlinmvvm.comm.client.AuthRetrofit
import com.jydd.singlekotlinmvvm.comm.client.apis.AuthApis
import com.jydd.singlekotlinmvvm.comm.model.db.DithubDatabase
import com.jydd.singlekotlinmvvm.comm.model.request.CreateAuthorization
import com.jydd.singlekotlinmvvm.comm.model.response.UserInfo

/**
 * created by 韦敏敏
 * on 2020/1/21
 */
class UserDataSource(
    private val context: Context,
    private val authRetrofit : AuthRetrofit
) : BaseDataSource() {
    private var apis: AuthApis ? = null
    private val database : DithubDatabase = Room.databaseBuilder(
        context.applicationContext,
        DithubDatabase::class.java,
        "dithub_db"
    ).build()
    fun setUserInfo(userName: String, password: String){
        authRetrofit.setUserInfo(userName, password)
        apis = authRetrofit.retrofit.create(AuthApis::class.java)
    }
    suspend fun authToken(onSuccess: () -> Unit, onError : (error: Exception) -> Unit){
        val createAuthorization = CreateAuthorization(
            clientId = GithubConfig.CLIENT_ID,
            clientSecret = GithubConfig.CLIENT_SECRET,
            note = GithubConfig.NOTE
        )
        request(
            call = {
                val authResult = apis?.auth(createAuthorization)
                val token = authResult?.token ?: ""
                context.getSharedPreferences(Constant.AccountConst.SP_ACCOUNT, Context.MODE_PRIVATE)
                    .edit {
                        putString(Constant.AccountConst.KEY_TOKEN, token).apply()
                    }
                val userInfo = apis?.getUserInfo(accessToken = token)
                userInfo?.run {
                    database.runInTransaction {
                        database.userDao().updateUser(this)
                    }
                }
                onSuccess.invoke()
            }
        , onError = { onError.invoke(it)})
    }
    suspend fun currUser() : UserInfo? {
        return database.userDao().currUser()
    }

}